//201902104047 周润恺
package cn.edu.sdjzu.xg.bysj.controller.basic;

import cn.edu.sdjzu.xg.bysj.domain.OpenArea;
import cn.edu.sdjzu.xg.bysj.service.OpenAreaService;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import lombok.extern.slf4j.Slf4j;
import util.Condition;
import util.ControllerHelper;
import util.JSONUtil;
import util.Pagination;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;
import java.util.Collection;
import java.util.List;
/**
 * 将所有方法组织在一个Controller(Servlet)中
 *
 * @author 1033299034@qq.com
 */

@WebServlet("/basic/openArea.ctl")
@Slf4j
public class OpenAreaController extends HttpServlet {
    /**
     * 增加
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        //设置请求字符编码为UTF-8
        // request.setCharacterEncoding("UTF-8");
        //设置响应字符编码为UTF-8
        // response.setContentType("application/json;charset=UTF-8");

        //创建JSON对象respMessage_jsonObj，以便往前端响应信息
       JSONObject respMessage_jsonObj = new JSONObject();
        try {
            String request_str_json = JSONUtil.getJSON(request);
            OpenArea toAddOpenArea = JSON.parseObject(request_str_json, OpenArea.class);
            OpenAreaService.getInstance().add(toAddOpenArea);
            respMessage_jsonObj.put("message","增加成功");
            log.trace("增加成功");
        } catch (SQLException e){
            respMessage_jsonObj.put("message","数据库操作异常");
            log.error("数据库操作异常" + e.getMessage());
        } catch (Exception e){
            respMessage_jsonObj.put("message","网络异常");
            log.error("网络异常" + e.getMessage());
        } finally {
            response.getWriter().println(respMessage_jsonObj);
        }
    }
    /**
     * 删除
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void doDelete(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        //request.setCharacterEncoding("UTF-8");
        //response.setContentType("application/json;charset=UTF-8");

        //创建JSON对象respMessage_jsonObj，以便往前端响应信息
        JSONObject respMessage_jsonObj = new JSONObject();
        try {
            //将request参数转换为JSON字串
            String request_json_str = JSONUtil.getJSON(request);
            //将请求body解析为要删除的对应的JSONObject对象(可能是{"id":1})
            JSONObject idOfTeacherToDelete_jsonObj = JSON.parseObject(request_json_str);
            //从JSONObject对象中读取键“id”的值（Java Object对象），
            Object id_obj = idOfTeacherToDelete_jsonObj.get("id");
            int id_int = Integer.parseInt(id_obj.toString());
            log.trace("OpenArea删除id" + id_int);
            OpenAreaService.getInstance().delete(id_int);
            respMessage_jsonObj.put("message", "删除成功");
            log.trace("删除成功");
        } catch (SQLException e) {
            respMessage_jsonObj.put("message", "数据库操作异常");
            log.error("数据库异常" + e.getMessage());
        } catch (Exception e) {
            respMessage_jsonObj.put("message", "网络异常");
            log.error("网络异常" + e.getMessage());
        } finally {
            response.getWriter().println(respMessage_jsonObj);
        }
    }

    /**
     * 修改
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void doPut(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        //request.setCharacterEncoding("UTF-8");
        //response.setContentType("application/json;charset=UTF-8");

        //创建JSON对象respMessage_jsonObj，以便往前端响应信息
        JSONObject respMessage_jsonObj = new JSONObject();
        try {
            String request_json_str = JSONUtil.getJSON(request);
            log.trace(request_json_str);
            OpenArea openArea = JSON.parseObject(request_json_str, OpenArea.class);
            OpenAreaService.getInstance().update(openArea);
            respMessage_jsonObj.put("message","更新成功");
            log.trace("更新成功");
        } catch (SQLException e){
            respMessage_jsonObj.put("message","数据库异常");
            log.error("数据库异常" + e.getMessage());
        } catch (Exception e){
            respMessage_jsonObj.put("message","网络异常");
            log.error("网络异常" + e.getMessage());
        } finally {
            response.getWriter().println(respMessage_jsonObj);
        }
    }

    /**
     * 查询
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //创建JSON对象respMessage_jsonObj，以便往前端响应信息
        JSONObject respMessage_jsonObj = new JSONObject();

        //设置响应字符编码为UTF-8
        //response.setContentType("application/json;charset=UTF-8");

        //将request body转换为JSON字串
        String req_jsonStr = JSONUtil.getJSON(request);
        //将request body解析为JSONObject对象
        JSONObject req_jsonObj = JSON.parseObject(req_jsonStr);
        //如果请求body为空
        if (req_jsonObj == null) {
            respMessage_jsonObj.put("message", "未收到请求信息！");
            response.getWriter().println(respMessage_jsonObj);
            log.error("未收到请求消息");
            return;
        }
        //从JSONObject对象中读取键“id”的值（Java Object对象），req_jsonObj可能是{"id":？}
        Object id_obj = req_jsonObj.get("id");
        try {
            //如果id_Obj != null, 说明请求数据有id键，是请求某个教师对象
            if (id_obj != null) {
                int id_int = Integer.parseInt(id_obj.toString());
                responseOpenArea(response,id_int);
                log.trace("查找id" + id_int);
            } else {
                //请求中包含条件和分页信息，需要响应多个教师对象，读取分页信息，形成分页对象
                //从JSONObject对象中读取 “pagination” 键对应的值(JSONObject对象)
                Pagination pagination = ControllerHelper.getPagination(req_jsonObj);
                //从请求JSONObject对象中读取键“condition”对应的值(描述查询条件的JSONArray对象)
                List<Condition> conditionList = ControllerHelper.getConditions(req_jsonObj);
                //响应多个教师信息，其中condition, pagination两个对象引用为空是可能的
                this.responseOpenAreas(response, conditionList, pagination);
            }
        } catch (SQLException e){
            respMessage_jsonObj.put("message","数据库异常");
            log.error("数据库异常"+ e.getMessage());
        } catch(Exception e){
            respMessage_jsonObj.put("message","网络异常");
            log.error("网络异常" + e.getMessage());
        }
        finally {
            response.getWriter().println(respMessage_jsonObj);
        }
    }

    private void responseOpenArea(HttpServletResponse response, int id) throws SQLException, IOException {
        //根据id查找
        OpenArea openArea = OpenAreaService.getInstance().find(id);
        //查找到的openArea'解析为json字串
        String openArea_json = JSON.toJSONString(openArea);
        //响应回前端
        response.getWriter().println(openArea_json);
    }

    private void responseOpenAreas(HttpServletResponse response , Collection<Condition> conditions, Pagination pagination) throws IOException, SQLException {
        //按照分页于条件查询对象集合
        Collection<OpenArea> openAreas = OpenAreaService.getInstance().findAll(conditions,pagination);
        //解析为json字串
        String openAreas_json = JSON.toJSONString(openAreas, SerializerFeature.DisableCircularReferenceDetect);
        //新建response_json对象，以便向前台响应消息
        JSONObject response_json = new JSONObject();
        //元组总数
        response_json.put("totalNum",pagination.getTotalNum());
        //查找到的对象集合
        response_json.put("data",openAreas_json);
        //响应回前端
        response.getWriter().println(response_json);
    }

}
